using Microsoft.EntityFrameworkCore;
using MyHomeworkWebAPi.Models.ef;
using MyHomeworkWebAPi.Models.Request;

namespace MyHomeworkWebAPi.Services
{
    /// <summary>
    /// 消息服务实现类
    /// </summary>
    public class MessageServices : IMessageServices
    {
        private readonly SecondHandTradingPlatformContext _context;

        /// <summary>
        /// 构造函数，注入数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public MessageServices(SecondHandTradingPlatformContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有消息
        /// </summary>
        public async Task<List<Message>> GetAllAsync()
        {
            return await _context.Messages.ToListAsync();
        }

        /// <summary>
        /// 根据ID获取消息
        /// </summary>
        public async Task<Message?> GetByIdAsync(Guid messageId)
        {
            return await _context.Messages.FindAsync(messageId);
        }

        /// <summary>
        /// 创建消息
        /// </summary>
        public async Task<Message> CreateAsync(MessageCreateRequest request)
        {
            var message = new Message
            {
                MessageId = Guid.NewGuid(),
                UserId = request.UserId,
                Content = request.Content,
                IsRead = 0,
                CreateTime = DateTime.Now
            };

            await _context.Messages.AddAsync(message);
            await _context.SaveChangesAsync();
            return message;
        }

        /// <summary>
        /// 删除消息
        /// </summary>
        public async Task<bool> DeleteAsync(Guid messageId)
        {
            var message = await _context.Messages.FindAsync(messageId);
            if (message == null)
            {
                return false;
            }

            _context.Messages.Remove(message);
            await _context.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 获取用户的消息列表
        /// </summary>
        public async Task<List<Message>> GetByUserIdAsync(Guid userId)
        {
            return await _context.Messages
                .Where(m => m.UserId == userId)
                .OrderByDescending(m => m.CreateTime)
                .ToListAsync();
        }

        /// <summary>
        /// 标记消息为已读
        /// </summary>
        public async Task<Message> MarkAsReadAsync(Guid messageId)
        {
            var message = await _context.Messages.FindAsync(messageId)
                ?? throw new Exception("消息不存在");

            message.IsRead = 1;
            await _context.SaveChangesAsync();
            return message;
        }

        /// <summary>
        /// 获取用户未读消息数量
        /// </summary>
        public async Task<int> GetUnreadCountAsync(Guid userId)
        {
            return await _context.Messages
                .CountAsync(m => m.UserId == userId && m.IsRead == 0);
        }
    }
} 